window.onbeforeunload = confirmExit;
document.onkeydown = keyevent;
function confirmExit(){
	if (needsToBeSaved){
		return "Please click on the Save button to save any changes, or the Cancel the button to exit the page.";
	}
}

function adjust(){
	var adjust = document.getElementById("adjust");		
	var addBy = Number(adjust.value);
	var newArray = new Array()
	for (timeIndex=0; timeIndex<originalTimes.length; timeIndex++){
		var newTime = originalTimes[timeIndex] - addBy;
		newTime = Math.round(newTime * 100) / 100;
		newArray.push(newTime);
	}
	times = newArray;
}
function adjustSelection(){
	var value = document.getElementById("time_adjuster").value;		
	var addBy = Number(value);
	var addBy  =  addBy / 10;
	var newArray = new Array()
		//alert(originalTimes.length);
	for (timeIndex=0; timeIndex<originalTimes.length; timeIndex++){
		var newTime = originalTimes[timeIndex] - addBy;
		newTime = Math.round(newTime * 100) / 100;
		newArray.push(newTime);
	}
	times = newArray;
}

function adjustSlider(value){
	value = 5 - value;
	var addBy  =  value / 10;
	alert(addBy);
	//var addBy = Number(addBy);
	var newArray = new Array();
	for (timeIndex=0; timeIndex<originalTimes.length; timeIndex++){
		var newTime = originalTimes[timeIndex] - addBy;
		alert(newTime);
		newArray.push(newTime);
		//alert(times[timeIndex] + " " + originalTimes[timeIndex]);
	}
	times = newArray;
}

function shiftTimes(arrayToCopy, subtractBy){
	size = arrayToCopy.length;

	for (y = 0; y < arrayToCopy.length; y++){
		var newValue = arrayToCopy[y] - Number(subtractBy);
		newValue = Math.round(newValue * 100) / 100;
		//alert(newValue);
		newArray.push(newValue);

	}
	return newArray;
}

var needsToBeSaved;
function changeOccurred(){
	needsToBeSaved = true;
	document.getElementById("save").disabled = false;
}


var latestAdjustedWord;
//var previousHighestWordChecked;

function markAllAdjustedWordsAsAdjusted(){
	for (i =0; i < adjustedWordIds.length; i++){
		var id = "w" + adjustedWordIds[i];
		var element = document.getElementById(id);
		markWordAsAdjusted(element);
	}
}

function markWordAsAdjusted(element){
	element.style.fontWeight = "bold";
	element.style.fontStyle = "italic";
	//element.style.fontSize = "110%";
	element.setAttribute("adjusted", "y");
}

function changeSelectedWordToTime(newTime){
	newTime = Math.round(newTime * 100) / 100;
	times[currentNum] = newTime;
	if (currentElem != latestAdjustedWord){
		var adjusted = currentElem.getAttribute("adjusted");
		if (adjusted == null){
			markWordAsAdjusted(currentElem);
			latestAdjustedWord = currentElem;
			adjustedWordIds.push(currentNum);
		}
	}


	/*if (currentNum > highestIdAdjusted){
		highestIdAdjusted = currentNum;		
		if (latestAdjustedWord!= null){
			//latestAdjustedWord.style.border = "0px dotted black";
			latestAdjustedWord.style.fontSize = "100%";
			latestAdjustedWord.style.backgroundColor = "#FFFFFF";
			//currentElem.style.fontWeight = "normal";
		}
		//currentElem.style.border = "1px dotted red";
		currentElem.style.fontSize = "110%";
		currentElem.style.backgroundColor = "#FFDDFF";
		latestAdjustedWord= currentElem;
		//document.getElementById("message").innerHTML = "new time: " + newTime;
	}*/
	playAt(newTime);
	document.getElementById("message").innerHTML = "time: " + newTime;
	changeOccurred();
}
function keyevent(evt){
	if (evt.keyCode == 187){
		var newTime = times[currentNum] + .1;
		changeSelectedWordToTime(newTime);
	}
	else if (evt.keyCode == 189){
		var newTime = times[currentNum] - .1;
		changeSelectedWordToTime(newTime);
	}
	else if (evt.keyCode == 221){  // close bracket
		var newTime = times[currentNum] + .05;
		changeSelectedWordToTime(newTime);		
	}
	else if (evt.keyCode == 219){ // open bracket
		var newTime = times[currentNum] - .05;
		changeSelectedWordToTime(newTime);
	}
	/*else if (evt.keyCode == 189){
		var newTime = times[currentNum] - .1;
		newTime = Math.round(newTime * 100) / 100;
		times[currentNum] = newTime;
		playAt(newTime);
		document.getElementById("message").innerHTML = "new time: " + newTime;
	}*/
	else if (evt.keyCode == 13){
		var time = times[currentNum];
		playAt(time);
		markWordAsAdjusted(currentElem);
		changeOccurred();
		document.getElementById("message").innerHTML = "time: " + time;
	}
	/*else if (evt.keyCode == 70){
		alert(times);
	}*/
}

function stopNow(){
	timeID = -1;
	player.pause();
}
function playAt(time){
	if (soundLoaded){
		player.pause();
		if (timeID != -1){
			clearTimeout(timeID);
		}
	//	alert(time);
		player.currentTime = time;
		player.play();
		timeID = setTimeout("stopNow()",1100);
	}
}

function addMouseOver(elem){
	elem.onmouseover = function(event){ giveFocus(event)};
}

var timeID;
var counter = 0;

function verifyBrowserCompatibility(){
	var agent = navigator.userAgent;
	
	if ( agent.indexOf("Safari") == -1 || agent.indexOf("Chrome") != -1){
		checkin();
		alert("The sound integration task requires the use of Safari at this time.");
		window.location = "/eng/volunteering.html"
		return false;
	}
	return true;
}
function init(){
	verifyBrowserCompatibility()
	originalTimes = times;
	var counter = 0;
	var id = "w" + counter++;
	var elem = document.getElementById(id);
	while (elem != null){
		addMouseOver(elem);
		id = "w" + counter++;
		elem = document.getElementById(id);
	}
	player =  document.getElementsByTagName('audio')[0];;
	player.addEventListener("canplaythrough", function() { onCanPlayThrough() }, true);
	markAllAdjustedWordsAsAdjusted();
}

var soundLoaded = false;
function onCanPlayThrough(){
	soundLoaded = true;
}

function exit(){
	checkin();
	/*if (wordCount == highestIdChecked){
		window.location = "/user/readings/reading_question.jsp?id=" + id;
	}
	else{
		window.location = "/user/readings/reading_view.jsp?id=" + id;
	}*/
}

function tryToExit(){
	var message = document.getElementById("message");
	message.innerHTML = "Exiting";
	var exitButton = document.getElementById("exit");
	exitButton.disabled = true;
	if (needsToBeSaved){
		$("#confirmation").dialog({
			modal: true,
			title: useroptionString,
			buttons: { 
			"Cancel": function() { $(this).dialog("close"); },
			"Exit": function() { $(this).dialog("close"); exit(); }
			}
		});
	}
	else{
		exit();
	}
	//window.location = "/user/readings/reading_view.jsp?id=" + id;
}

function enableSaveButtons(){
	var save = document.getElementById("save");
	var saveAndContinue = document.getElementById("saveAndContinue");
	save.disabled=true
	saveAndContinue.disabled=true;
}

function disableSaveButtons(){
	var save = document.getElementById("save");
	//var saveAndContinue = document.getElementById("saveAndContinue");
	save.disabled=true
	//saveAndContinue.disabled=true;
}

var currentElem;
var currentNum;
	
function giveFocus(evt){
	if (currentElem != null){
		currentElem.style.border = "0px dotted black";
	}
	var id = evt.target.id;
	currentNum = id.substring(1);

	/*if (currentNum > highestIdChecked){
		highestIdChecked = currentNum;
	}*/

	currentElem = document.getElementById("w" + currentNum);
	currentElem.style.border = "1px dotted black";
	playAt(times[currentNum]);
}

function checkin(){
	$.ajax({
  type: 'POST',
  url: "/user/readings/checkin_sound.jsp",
  data: {id: id},
  success: function(msg) {
	//window.location = "/user/readings/reading_view.jsp?id=" + id;
	window.location = "/eng/volunteering.html";
  },
  error:function(request,error){ alert("An error occurred while saving: " + error); },
  dataType: "xml"
});	
}


function save(){
	var message = document.getElementById("message");
	message.innerHTML = "Saving..";
	$.ajax({
  type: 'POST',
  url: "/user/readings/sound_save.jsp",
  data: {id: id, times: times.toString(), adjustedWordIds: adjustedWordIds.toString()},
  success: function(msg) {
	//var saveButton = document.getElementById("save_button");
	disableSaveButtons();
	needsToBeSaved = false;
	var message = document.getElementById("message");
	message.innerHTML = "";
	//saveButton.disabled = true;
	// highestIdProcessed: highestIdChecked,
  },
  error:function(request,error){ alert("An error occurred while saving: " + error); },
  dataType: "xml"
});	
}